上一篇將 Semantic Kernel 成功在前端建立,今天要來針對這個前端的 APP 做一點優化的設計,將這個 APP 變的更人性化
這次的修改之一是加上 Notification,我們先來了解一下 Notification 可以做到的效果
以下是組成 Notification 的一些元素:
接著是可以使用的一些 Style
大文本樣式 (Big Text Style):
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle()
.bigText("這是一個很長的文本,可以顯示多行內容...");
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
// ... 其他設置
.setStyle(bigTextStyle);
收件箱樣式 (Inbox Style):
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle()
.addLine("第一行")
.addLine("第二行")
.addLine("第三行");
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
// ... 其他設置
.setStyle(inboxStyle);
大圖片樣式 (Big Picture Style):
Bitmap bigPicture = BitmapFactory.decodeResource(getResources(), R.drawable.big_picture);
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle()
.bigPicture(bigPicture)
.bigLargeIcon(null); // 隱藏大圖標
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
// ... 其他設置
.setStyle(bigPictureStyle);
其他我們還可以在 Notification 上做到一些簡單的按鈕、輸入的事件
為了能夠順利使用 Notification 還必須加上相關的權限才可以使用
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
這次會將 Notification 運用在傳回訊息時會提醒用戶分析的結果
首先建立我們的 Notification
private static final String CHANNEL_ID = "MyChannel";
private static final int NOTIFICATION_ID = 1;
private void createNotification() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{android.Manifest.permission.POST_NOTIFICATIONS}, 1);
}
CharSequence name = "My Notification Channel";
String description = "Channel for my app notifications";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
接著在回傳訊息的地方接上顯示 Notification 的 Function
private void getSemanticKernelResponse(String message) {
// 之前的程式碼
showNotification(history.getMessages().get(history.getMessages().size() - 1).getContent());
}
private void showNotification(String content) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notifications_active)
.setContentTitle("My Notification")
.setContentText(content)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}